package org.example.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        // 创建客户端线程组
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)  // 设置线程组
                     .channel(NioSocketChannel.class) // 设置客户端通道实现
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel ch) throws Exception {
                             ch.pipeline().addLast(new StringDecoder());
                             ch.pipeline().addLast(new StringEncoder());
                             ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                                 @Override
                                 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                     System.out.println("接收到服务器消息: " + msg);
                                 }
                                 
                                 @Override
                                 public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                     // 连接成功后发送消息
                                     ctx.writeAndFlush("Hello Server!");
                                 }
                             });
                         }
                     });

            // 连接服务器，异步连接，等待连接成功
            ChannelFuture future = bootstrap.connect("localhost", 8080).sync();

            // 等待客户端关闭连接
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
